/*
 * Created by SharpDevelop.
 * User: fatman
 * Date: 10/27/2008
 * Time: 3:45 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;

namespace CUALib
{
	/// <summary>
	/// Description of Window.
	/// </summary>
	public class Window : ConsoleControl
	{
		//IList<ConsoleControl> controls

		public Window(bool consoleExists)
			: base(consoleExists)
		{

			BackgroundColor=ConsoleColor.Black;
			if (!ConsoleExists)
				return;

			_allControls = new ConsoleControlCollection(null);

			this.Size = new Size(Console.BufferWidth, Console.BufferHeight);

			this.Redraw();
		}
		public override void Invalidate(Rectangle rect)
		{

			if (!Visible)
				return;
			//ConsoleColor oldbackgroundColor=Console.BackgroundColor;
			Console.BackgroundColor= this.BackgroundColor;
			
			
			
			Console.Clear();
			//Console.BackgroundColor= oldbackgroundColor;
			foreach (ConsoleControl cc in Controls)
			{
				//Console.WriteLine(cc);
				cc.Invalidate(rect);
			}
			return;/*
			if (!ConsoleExists)
				return;
			string line = new StringBuilder(DecorationSet[BoxDrawingDecorationNames.background].ToString(), rect.Width).ToString();
			for (int i = _location.Y + rect.Y; i < _location.Y + rect.Y + rect.Height; i++)
			{
				Console.SetCursorPosition(rect.X, i);
				Console.Write(line);
			}*/


		}



		private System.Drawing.Point _location = System.Drawing.Point.Empty;
		public override System.Drawing.Point Location
		{
			get
			{
				return _location;
			}
			set { }
		}


		public override ConsoleControl TopLevelParent
		{
			get
			{
				return this;
			}
		}

		private ConsoleControlCollection _allControls;
		public ConsoleControlCollection AllControls
		{
			get { return _allControls; }
		}


		private ConsoleControl _activeControl;

		public override ConsoleControl ActiveControl
		{
			get
			{
				return _activeControl;
			}
			set
			{
				if (_activeControl != null)
				{
					_activeControl.Focused = false;
					_activeControl.Invalidate();
				}
				_activeControl = value;

			}
		}



		public void WndProc(ConsoleKeyInfo cki)
		{
			ConsoleKey ck = cki.Key;
			switch (ck)
			{
				case ConsoleKey.Tab:
					ConsoleControl cc;
					if (ActiveControl == null)
					{
						cc = FindNextControl();
					}
					else
					{
						cc = ActiveControl.FindNextControl();
					}
					if(cc==this)
						cc=cc.FindNextControl();
					
					if(cc!=this)
						cc.Focus();
					//ActiveControl.FindNextControl().Focus();
					Invalidate(true);
					break;
			}

			ReceiveEvent(cki, true);
			

		}
	}
}
